package at.technikum.bic.ese.hatcam.services;

import java.io.File;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import at.technikum.bic.ese.hatcam.upload.UploadRunner;

public class UploadService extends Service {
	private static final String TAG = "Hatcam";
	
	public static boolean uploadRunning = false;
	
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		
		if(isHatcamActivated() && isOnline() && !uploadRunning) {
			uploadRunning = true;
			
			File sdCard = Environment.getExternalStorageDirectory();
			File hatcamFolder = new File(sdCard.getAbsolutePath() + "/hatcam");
			
			UploadRunner uploader = new UploadRunner(hatcamFolder.listFiles());
			Thread uploadThread = new Thread(uploader);
			uploadThread.start();
		}
	}

	private boolean isHatcamActivated() {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		boolean hatcamActivated = prefs.getBoolean("preference_activate", false);
		
		return hatcamActivated;
	}
	private boolean isOnline() {
		boolean isOnline = false;
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = null;
		if(cm != null) ni = cm.getActiveNetworkInfo();
		if(ni != null) isOnline = ni.isConnected();
		
		if(isOnline) Log.i(TAG, "Hatcam ist mit dem Internet verbunden!");
		else Log.i(TAG, "Hatcam ist offline");
		
		return isOnline;
	}
}
